package com.carrental.sms.servicce;


import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import com.carrental.framework.config.AliyunSmsConfig;
import com.carrental.sms.domain.SmsInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author LiangYi
 * @since 2022/3/24 23:21
 */
@Service
@Slf4j
public class AliyunSmsService {
    @Autowired
    private AliyunSmsConfig aliyunSmsConfig;
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret,String endpoint) throws Exception {
        Config config = new Config()
            // 您的AccessKey ID
            .setAccessKeyId(accessKeyId)
            // 您的AccessKey Secret
            .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = endpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public Boolean sendSms(SmsInfo smsInfo) throws Exception {
        Client client;
        try {
            client = createClient(aliyunSmsConfig.getAccessKeyId(),aliyunSmsConfig.getAccessKeySecret(),aliyunSmsConfig.getEndpoint());
        } catch (Exception e) {
            throw new RuntimeException("创建短信Client失败！");
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
            .setSignName("阿里云短信测试")
            .setTemplateCode("SMS_154950909")
            .setPhoneNumbers(smsInfo.getPhoneNumber())
            .setTemplateParam(smsInfo.getTemplateParam());
        log.info("短信请求参数："+sendSmsRequest.getPhoneNumbers()+":"+sendSmsRequest.getTemplateParam());
        System.out.println("短信请求参数："+sendSmsRequest.toString());
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response=client.sendSms(sendSmsRequest);
        log.info("短信返回参数："+response.getBody().getMessage());
        System.out.println("短信返回参数："+response.toString());
        return true;
    }

    public Boolean sendEmail(){
        return true;
    }
}
